package kr.hkit.androidcomplete02.XMLparser;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import kr.hkit.androidcomplete02.R;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.sax.StartElementListener;
import android.widget.ListView;

public class Pull_parserAcitivity extends Activity {
	
	private ListView list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.network_xmlparser);
		list = (ListView) findViewById(R.id.listView);
		
		new ParsingXML().execute("order.xml");
		
	}
	
	private class ParsingXML extends AsyncTask<String, Void, ArrayList<Item>> {
		private ProgressDialog progressDlg;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDlg = ProgressDialog.show(Pull_parserAcitivity.this, "Wait", "xml parsing...");
		}
		
		@Override
		protected void onPostExecute(ArrayList<Item> result) {
			super.onPostExecute(result);
			MyAdapter adapter = new MyAdapter(Pull_parserAcitivity.this, result);
			progressDlg.dismiss();
			list.setAdapter(adapter);
			
		}
		
		@Override
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while((str=br.readLine())!=null){
					sb.append(str);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return parsingXml(sb.toString());
		}

		
		//Pull parser는 이부분
		private ArrayList<Item> parsingXml(String xml) {
			ArrayList<Item> arItem = new ArrayList<Item>();
			Item itemClass = null;
			boolean initItem = false; //SAX 파서의 initItem과 같은 역할.
			int eventType;
			try {
				XmlPullParserFactory factory =  XmlPullParserFactory.newInstance();
				XmlPullParser parser = factory.newPullParser();
				
				parser.setInput(new StringReader(xml));
				//SAX와 마찬가지로 이벤트기반
				//int eventType = parser.getEventType();
				
				while((eventType=parser.next()) != XmlPullParser.END_DOCUMENT){//문서의 끝이아니라면 계속읽기
					switch(eventType){
					case XmlPullParser.START_DOCUMENT:
						break;
					case XmlPullParser.START_TAG:
						if(parser.getName().equalsIgnoreCase("item")){
							initItem = true;
							itemClass = new Item();
						}
						if(parser.getAttributeCount()>0){ //속성도 여기서
							for(int i = 0; i< parser.getAttributeCount(); i++){
								if (parser.getAttributeName(i).equalsIgnoreCase("price")){
									itemClass.setItemPrice(Integer.parseInt(parser.getAttributeValue(i)));
								}else{
									itemClass.setMakerName(parser.getAttributeValue(i));
								}
							}
						}
						break;
						
					case XmlPullParser.TEXT: //아이템 네임은 여기서 가지고옴
						if (initItem){
							itemClass.setItemName(parser.getText());
							initItem = false;
						}
						break;
						
					case XmlPullParser.END_TAG:
						if (parser.getName().equalsIgnoreCase("item")){
							arItem.add(itemClass);
						}
						break;
					}
					//eventType = parser.next();
				}
				
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return arItem;
		}
	}
}
